"""
Screenshot utility using Imagemagick
Copyright (c) 2006 Peter Moberg <moberg.peter@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

On Debian systems, the complete text of the GNU General Public
License can be found in /usr/share/common-licenses/GPL file.
"""

import sys
import os
from stat import *
import tempfile

class Screenshot:
	def __init__(self):
		self.__cmdImport = self.__locateExecutable("import")
		self.__cmdMogrify = self.__locateExecutable("mogrify")

	def __locateExecutable(self,name):
		""" Locates path to a given executable, empty if executable where not found """
		execPath = []
		path = os.environ['PATH'].split(os.pathsep)
		
		for dir in path:
			ident = ()
			filename = os.path.join(dir,name)
			
			try:
				st = os.stat(filename)
			except os.error:
				continue
			if not S_ISREG(st[ST_MODE]):
				print filename + " is not a disk file"
			else:
				mode = S_IMODE(st[ST_MODE])
				if mode & 0111:
					if not ident:
						execPath.append(filename)
						ident = st[:3]
	
		return execPath
	
	def isPossible(self):
		""" Determines if this module is able to take an screenshot """
		return (len(self.__cmdImport) > 0 and len(self.__cmdMogrify) >0)
	
	def takeScreenshot(self, path=None, fileName="preview.png", callback=None):
		""" Take a screenshot """
		if len(self.__cmdImport) <= 0: 
			print "ERROR: Can't find Imagemagick executeable 'import', make sure your PATH is set correctly"
			return
		
		if len(self.__cmdMogrify) <= 0: 
			print "ERROR: Can't find Imagemagick executeable 'mogrify', make sure your PATH is set correctly"
			return
		
		if path == None:
			path = tempfile.mkdtemp()
			
		file = os.path.join(path,fileName)
		print "Calling import"
		os.system(self.__cmdImport[0] + " -window root -geometry 640 " + file)
		if callback != None:
			callback(True)
		
		#print "Resizeing image"
		#os.system(self.__cmdMogrify[0] + " -geometry 640 " + file)
	
		if callback != None:
			callback(False)
		
		return file
			
